<template>
  <div class="alarmRecord">
    <div class="searchDiv">
      <div style="font-weight:bold;background:#f5f5f5;margin-bottom:10px;padding:5px;">当前机组编号：{{aircrewNumber}}</div>
      <Form :model="searchItem" :label-width="90">
        <Row :gutter="10">
          <Col span="6">
                    <FormItem label="监测状态">
                      <Select v-model="searchItem.alarmAlias" clearable filterable>
                          <Option v-for="(item, index) in alarmAliasList" :value="item.displayName" :key="index">{{item.displayName}}</Option>
                      </Select>
                    </FormItem>
           </Col>
           <Col span="6">
            <FormItem label="报警时间">
              <DatePicker
                type="datetimerange"
                @on-change="searchtime1"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间"
                style="width: 100%"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="确认时间">
              <DatePicker
                type="datetimerange"
                @on-change="searchtime2"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间"
                style="width: 100%"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
                    <FormItem label="确认状态">
                      <Select v-model="searchItem.status" clearable>
                        <Option value="2">已确认</Option>
                        <Option value="1">未确认</Option>
                     </Select>
                    </FormItem>
           </Col>
          <Col span="24" style="text-align:center;">
            <Button @click="$router.go(-1)" class="marRight">返回上一页</Button>
            <Button type="primary" @click="searchItem.pageNo=1;getDataList()" class="marRight">查询</Button>
            <Button type="success" @click="down">导出Excel</Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Table :loading="loading" border :columns="columns" :data="tableData"></Table>
     <Page show-total :current="searchItem.pageNo" :total="total" :page-size="searchItem.pageSize"  style="margin:20px auto;text-align:center" @on-change="changePage" />
    <!-- 新增弹窗开始 -->
    <Modal :mask-closable="false" v-model="modal1" title="查看详情" width="600" class="ckxq" @on-ok="ok">
        <Form :label-width="100">
            <FormItem label="测点名称：">
                {{formItem.pointName}}  <span style="margin-left:100px;">报警值：</span>{{Number(formItem.value).toFixed(2)}}
            </FormItem>
            <FormItem label="报警时间：">
                 {{formItem.alarmStartTime}}
            </FormItem>
            <FormItem label="报警等级：">
                {{formItem.alarmAlias}}
            </FormItem>
            <FormItem label="评估报警：">
                <RadioGroup v-model="formItem.assessCallType" @on-change="radioChange">
                    <Radio label="0" >确认报警</Radio>
                    <Radio label="1" >单点取消</Radio>
                    <Radio label="2" >阶段取消</Radio>
                </RadioGroup>
            </FormItem>
            <FormItem label="截止时间选择：" v-show="formItem.assessCallType=='2'">
                 <!-- <Date-picker
                  type="datetime"
                  placeholder="选择时间"
                  v-model="formItem.startTime"
                  @on-change="time1"
                  style="width: 200px;"></Date-picker> -->
                  <Date-picker
                  type="datetime"
                  v-model="formItem.endTime"
                  :options="options"
                  placeholder="选择时间"
                  @on-change="time2"
                  style="width: 200px"></Date-picker>
            </FormItem>
            <FormItem label="故障原因：">
                 <Select v-model="formItem.faultReasonStatusDictId" clearable filterable @on-change="getSelect1">
                          <Option v-for="(item, index) in faultReasonList" :value="item.id" :key="index">{{item.displayName}}</Option>
                 </Select>
            </FormItem>
            <FormItem label="故障描述：">
                <Input type="textarea" :maxlength="50" v-model="formItem.faultDesc" placeholder="请输入描述"></Input>
            </FormItem>
            <FormItem label="检修建议：">
                 <Select v-model="formItem.overhaulSuggestDictId" clearable filterable @on-change="getSelect2">
                          <Option v-for="(item, index) in overhaulSuggestList" :value="item.id" :key="index">{{item.displayName}}</Option>
                 </Select>
            </FormItem>
            <FormItem label="建议描述：">
                <Input type="textarea" :maxlength="50" v-model="formItem.suggestDesc" placeholder="请输入描述"></Input>
            </FormItem>
            <FormItem label="上传报告：">
                <Upload
                     :headers='fileheader'
                          :on-success='fileSuccess'
                          :show-upload-list='false'
                          :action="apihost+'/admin-api/admins/upload/uploadFile'">
                    <Button icon="ios-cloud-upload-outline">选择文件</Button>
                </Upload>
                <ul class="upList" v-if="uploadList.length>0">
                    <li v-for="(item,index) in uploadList">
                      <span style="float:left;width:330px;overflow:hidden;">{{item.substring(item.lastIndexOf('/')+1)}}</span>
                      <Button size="small"  @click="xiazai(item)" type="primary">下载文件</Button>
                      <Button size="small"  @click="fileRemove(index)" type="error">删除</Button>
                    </li>
                </ul>
                <!-- <Button  v-if="formItem.url"  @click="xiazai" type="primary">查看文件</Button> -->
            </FormItem>
           </Form>
           <div slot="footer">
               <Button @click="addWtgz">添加至问题跟踪</Button>
               <!-- <Button>上传报告</Button> -->
               <Button type="primary" :loading="btnClick" @click="confirmMsg">确认处理</Button>
           </div>
    </Modal>
    <!-- 新增弹窗结束 -->
  </div>
</template>

<script>
import { getTableData, confirmAlarm,addIssure,importExcel } from '@/api/alarmRecord'
import { getToken } from '@/libs/util'
import {getSelectOption} from '@/api/select'
export default {
  data () {
    return {
      btnClick:false,
      options: {
                   disabledDate (date) {
                        return date && date.valueOf() < Date.now()
                    }
                },
      uploadList:[],
      defaultfileList:[],
      modal1: false,
      faultReasonList:[],
      overhaulSuggestList:[],
      fileheader: {
        Authorization: 'Bearer ' + (getToken() ? getToken() : '')
      },
      loading:true,
      total:0,
      alarmAliasList:[],
      aircrewNumber:this.$route.query.aircrewNumber,
      searchItem: {
        startCallTime:'',
        endCallTime:'',
        startAcknowledgementTime:'',
        endAcknowledgementTime:'',
        equipmentId:this.$route.query.equipmentId,
        status:'',
        pageNo: 1,
        pageSize: 10
      },
      fileheader: {
        Authorization: 'Bearer ' + (getToken() ? getToken() : '')
      },
      formItem: {

      },
      columns: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'center'
        },
        {
          title: '报警测点',
          key: 'pointName'
        },
        {
          title: '监测状态',
          key: 'alarmAlias'
        },
        {
          title: '报警时间',
          key: 'alarmStartTime'
        },
        {
          title: '确认时间',
          key: 'acknowledgementTime'
        },
        {
          title: '报警原因',
          key: 'faultReasonStatusDisplayName'
        },
        {
          title: '确认状态',
          key: 'status',
          render: (h, params) => {
            return h('div', [
              params.row.status == 2 ? '已确认' : '未确认'
            ])
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 100,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.edit(JSON.stringify(params));
                    }
                  }
                },
                '查看详情'
              )
            ])
          }
        }
      ],
      tableData: [],

    }
  },
  methods: {
    down(){
      importExcel(this.searchItem).then(res => {
           const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});

        const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        console.log('ie:' + ie);
        console.log('ieVer:' + ieVer);
        if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob, '报警记录.xlsx');
        } else {
            const url = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', '报警记录.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }


        // const blob = new Blob([res]);//处理文档流
        //   const fileName = '报警记录.xlsx';
        //   const elink = document.createElement('a');
        //   elink.download = fileName;
        //   elink.style.display = 'none';
        //   elink.href = URL.createObjectURL(blob);
        //   document.body.appendChild(elink);
        //   elink.click();
        //   URL.revokeObjectURL(elink.href); // 释放URL 对象
        //   document.body.removeChild(elink);
      })
    },
    searchtime1 (e) {
       this.searchItem.startCallTime = e[0];
       this.searchItem.endCallTime = e[1];
    },
    searchtime2 (e) {
      this.searchItem.startAcknowledgementTime = e[0];
       this.searchItem.endAcknowledgementTime = e[1];
    },
    time1 (e) {
      this.formItem.startTime = e
    },
    time2 (e) {
      this.formItem.endTime = e
    },
    radioChange (e) {
      console.log(this.formItem.assessCallType)
    },
    fileRemove(index){
      this.uploadList.splice(index,1)
      this.formItem.url = this.uploadList.join(',')
    },
    fileSuccess (response, file, fileList) {
      // let dataArry=[];
      // for(let i=0;i<fileList.length;i++){
      //   if(fileList[i].response.data){
      //     dataArry.push(fileList[i].response.data)
      //   }
      // }
      // this.uploadList=dataArry;
      // this.formItem.url = dataArry.join(',')
      this.uploadList=this.uploadList.concat(response.data);
      this.formItem.url = this.uploadList.join(',')
      this.$Message.info('报告上传成功！')
    },
    xiazai(src){
        var eleLink = document.createElement('a');
        eleLink.download = src.substring(src.lastIndexOf('/')+1);
        eleLink.style.display = 'none';
        eleLink.href = src;
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    },
    changePage (pageNo) {
      this.searchItem.pageNo = pageNo
      this.getDataList()
    },
    getDataList () {
      console.log('开始获取信息')
      let that = this
      getTableData(that.searchItem).then(res => {
        console.log(res.data, '报警记录列表')
        this.tableData = res.data.list
        this.total=res.data.total;
        this.loading=false;
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    edit (params) {
      this.defaultfileList=[];
      this.formItem = JSON.parse(params).row;
      this.formItem.faultReasonStatusDictId=Number(this.formItem.faultReasonStatusDictId)
      this.formItem.overhaulSuggestDictId=Number(this.formItem.overhaulSuggestDictId)
      if(this.formItem.url!=null&&this.formItem.url!=''){
        this.uploadList=this.formItem.url.split(',')
      }else{
        this.uploadList=[]
      }

      this.modal1 = true
    },
    ok () {
      this.$Message.info('提交成功')
    },
    confirmMsg () {
      this.btnClick=true;
      confirmAlarm(this.formItem).then(res => {
        if (res.code == 0) {
          this.$Message.info('处理成功')
          this.modal1 = false;
          this.searchItem.pageNo=1;
          this.getDataList();
          this.btnClick=false;
        } else {
          this.$Message.info(res.message)
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    addWtgz () {
      // addIssure(this.formItem).then(res => {
      //   console.log(res.data)
      //   if (res.code == 0) {
      //     this.$Message.info('处理成功')
      //     this.modal1 = false
      //   } else {
      //     this.$Message.info(res.message)
      //   }
      // }).catch(err => {
      //   console.error('err>' + JSON.stringify(err))
      // })
       this.modal1 = false;
      this.$router.push(
        {
          path:'/problem/tefectTracking',
          query:{
            open:true,
            issue:this.aircrewNumber+"-"+this.formItem.pointName+'-'+this.formItem.alarmAlias,
            source:"状态监测",
            description:this.aircrewNumber+"-"+this.formItem.pointName+'-'+this.formItem.alarmAlias+'，报警时间:'+this.formItem.alarmStartTime+'，报警值:'+Number(this.formItem.value).toFixed(2),
            reasonAnalyze:this.formItem.faultReasonStatusDisplayName
          }
        }
      )
    },
    //获取监测状态
    getalarmAlias () {
      getSelectOption(
        {
          code: 'alarmAlias'
        }
      ).then(res => {
        this.alarmAliasList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    //获取故障原因
    faultReason () {
      getSelectOption(
        {
          code: 'faultReason'
        }
      ).then(res => {
        this.faultReasonList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    //获取检修建议
    overhaulSuggest () {
      getSelectOption(
        {
          code: 'overhaulSuggest'
        }
      ).then(res => {
        this.overhaulSuggestList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    getSelect1(e){
       var arry=this.faultReasonList.filter(item => item.id==e)
       this.formItem.faultReasonStatusDisplayName=arry[0].displayName
       this.formItem.faultReasonStatusValue=arry[0].value
    },
    getSelect2(e){
       var arry=this.overhaulSuggestList.filter(item => item.id==e)
       this.formItem.overhaulSuggestDisplayName=arry[0].displayName
       this.formItem.overhaulSuggestValue=arry[0].value
    },
  },
  mounted () {},
  created () {
    this.faultReason()
    this.overhaulSuggest()
    this.getalarmAlias()
    this.getDataList()
  },
  watch: {
  '$route' (to, from) {
    this.aircrewNumber=this.$route.query.aircrewNumber;
    this.searchItem.equipmentId=this.$route.query.equipmentId;
    this.getDataList()
  }
}
}
</script>

<style lang="less">
.alarmRecord {
  background: #fff;
  height: 100%;
  padding: 15px;
  font-size: 14px;
  .searchDiv {
      margin-bottom:15px;
    .marRight {
      margin-right: 15px;
    }
  }
  .ivu-form-item {
    margin-bottom: 15px;
  }
}
.baseTitle {
    font-weight: bold;
    font-size:16px;
    margin-bottom:10px;
  }
 .ckxq  {
   .ivu-form-item {
    margin-bottom: 10px;
  }
  .upList li {
    border-bottom:1px solid #eaeaea;
    height:40px;
    line-height:40px;
    padding:0px;
    margin:0px;
    overflow: hidden;
    list-style: none;
    .ivu-btn {
      float:right;
      margin-left:10px;
      margin-top:7px;
    }
  }
 }
</style>
